import { Component } from "react";
import { createPage, base, createPageIcon } from "nc-lightapp-front";
const { NCSelect, NCIcon, NCAffix } = base;
import { setSearch,setTable } from 'src/erm/sscrppublic/common/utils/setComponentUsed';

import WorkbenchDetail from "src/erm/sscrppublic/common/components/workbench-detail";
import pubMessage from 'src/erm/sscrppublic/common/utils/pubMessage';
import { initTemplate, listButtonClick, query } from "./events/index";
import presetVar from "./presetVar";
import requestApi from "./requestApi";
import {
    ProfileStyle,
    ProfileHead,
    ProfileBody,
    ButtonGroup,
    HeadCenterCustom,
    ProfileSearch
} from 'src/erm/sscrppublic/common/components/profile';
import sscOpenTo from 'src/erm/sscrppublic/common/utils/sscOpenTo';


import "./index.less";

class RpBillSearch extends Component {
  constructor(props) {
    super(props);
    //平台组件初始化
    setTable(props,presetVar.list),
    setSearch(props,presetVar.searchArea)
    let multiLang = this.props.MutiInit.getIntl(1056);
    // 201103DJCX-0001":"缩略显示"
    this.state = {
      showType: "list",
      fuzzyquerychild: [],
      menuShowType: {
        type: "icon-Group",
        title: "缩略显示"
        // title:multiLang && multiLang.get('201103DJCX-0001')
      }
    };
    this.pubMessage = new pubMessage(props);
    // 查询条件
    this.queryKey = {
      fuzzyQueryKey: [],
      orderByInfo:[],
      // 页信息
      pageinfo: {
        number: 1,
        size: 50,
        totalElements: 0,
        totalPages: 0
      },
      queryKey: {}
    };
    // 缓存查询结果数据
    this.data = {
      listRows: [],
      cardRows: []
    };

    // 延时控制标记
    // 翻页
    this.canChangPageFlag = true;
    // 模糊查询
    this.fuzzyKey = "";

    // 页面初始化
    initTemplate.call(this, props);
  }

  initScrollEvent() {
    const self = this;
    if (document.getElementById('WorkbenchDetail')) {
        document.getElementById('WorkbenchDetail').addEventListener('scroll', function (e) {
            const elem = e.target;
            if (self.canChangPageFlag && elem.scrollTop + elem.clientHeight >= e.target.scrollHeight - 100) {
                self.canChangPageFlag = false;
                query.queryData.call(self, true);
            }
        });
    }
    if (document.querySelector('.u-table-body')) {
        document.querySelector('.u-table-body').addEventListener('scroll', function (e) {
            const elem = e.target;
            if (self.canChangPageFlag && elem.scrollTop + elem.clientHeight >= e.target.scrollHeight - 100) {
                self.canChangPageFlag = false;
                query.queryData.call(self, true);
            }
        });
    }
    if (document.querySelector('.vertical-scroll-bar')) { // 解决单据向下无法滑动
      document.querySelector('.vertical-scroll-bar').addEventListener('scroll', function (e) {
          const elem = e.target;
          if (self.canChangPageFlag && elem.scrollTop + elem.clientHeight >= e.target.scrollHeight - 100) {
              self.canChangPageFlag = false;
              query.queryData.call(self, true);
          }
      });
    }
  }

//   componentDidMount() {
//     // Firefox
//     window.addEventListener("DOMMouseScroll", ev => {
//       ev = ev || window.event;
//       let onOff = null;
//       if (ev.detail < 0) {
//         onOff = true;
//       } else {
//         onOff = false;
//       }
//       let t = document.documentElement.scrollTop || document.body.scrollTop;
//       let h =
//         document.documentElement.scrollHeight || document.body.scrollHeight;
//       let bh =
//         document.documentElement.clientHeight || document.body.clientHeight;
//       if (
//         !onOff &&
//         h - bh - t < 30 &&
//         Number(this.queryKey.pageinfo.totalPages) > Number(this.queryKey.pageinfo.number) &&
//         this.canChangPageFlag
//       ) {
//         this.canChangPageFlag = false;
//         setTimeout(() => {
//           query.queryData.call(this, true);
//         }, 300);
//       }
//     });
//     // 其他浏览器
//     window.onmousewheel = ev => {
//       ev = ev || window.event;
//       let onOff = null;
//       if (ev.wheelDelta > 0) {
//         onOff = true;
//       } else {
//         onOff = false;
//       }
//       let t = document.documentElement.scrollTop || document.body.scrollTop;
//       let h =
//         document.documentElement.scrollHeight || document.body.scrollHeight;
//       let bh =
//         document.documentElement.clientHeight || document.body.clientHeight;
//       if (
//         !onOff &&
//         h - bh - t < 30 &&
//         Number(this.queryKey.pageinfo.totalPages) > Number(this.queryKey.pageinfo.number) &&
//         this.canChangPageFlag
//       ) {
//         this.canChangPageFlag = false;
//         setTimeout(() => {
//           query.queryData.call(this, true);
//         }, 300);
//       }
//     };
//   }
  menuClick = () => {
    // "201103DJCX-0001":"缩略显示",
    // "201103DJCX-0002":"列表显示",
    let multiLang = this.props.MutiInit.getIntl(1056);
    if (this.state.menuShowType.type == "icon-xingzhuang") {
      this.setState({
        menuShowType: {
          type: "icon-Group",
          title: multiLang && multiLang.get("201103DJCX-0001")
        },
        showType: "list"
      });
    } else {
      this.setState({
        menuShowType: {
          type: "icon-xingzhuang",
          title: multiLang && multiLang.get("201103DJCX-0002")
        },
        showType: "card"
      });
    }
  };
  // 模糊查询输入内容变化
  onFuzzyChange(data) {
    this.fuzzyKey = data;
    let newQueryKey = {};
    let multiLang = this.props.MutiInit.getIntl(1056);
    for (let child in this.queryKey) {
      newQueryKey[child] = this.queryKey[child];
    }
    newQueryKey.fuzzyQueryKey = data;
    setTimeout(
      (that, data) => {
        if (data == that.fuzzyKey) {
          requestApi.queryFuzzyKey({
            data: newQueryKey,
            success: data => {
              for (let childName in data.data) {
                data.data[childName].value =
                  data.data[childName].value + "=" + that.fuzzyKey;
                //105602BZCX-0049:包含
                data.data[childName].key =
                  data.data[childName].key + (multiLang && multiLang.get("201103DJCX-0007")) + that.fuzzyKey;
              }
              that.setState({ fuzzyquerychild: data.data });
            }
          });
        }
      },
      500,
      this,
      data
    );
  }
  // 模糊查询选择
  onFuzzySelected(data) {
    this.setState({ fuzzyquerychild: [] });
    // 更新查询条件
    this.queryKey.fuzzyQueryKey = data;
    // 查询数据
    query.queryData.call(this);
  }

  // 复制列表数据
  copyData(data) {
    let newData = {};
    newData.values = {};
    for (let child in data.values) {
      newData.values[child] = {
        display: data.values[child].display,
        value: data.values[child].value,
        scale: data.values[child].scale
      };
    }
    return newData;
  }
  searchClick(props, data, type) {
    this.queryKey.queryKey = data;

    query.queryData.call(this);
  }
  // 排序点击
  orderByClick(){
    query.queryData.call(this);
  }
  onRowDoubleClick = (values, idx, props, events) => {
    requestApi.openBill({
      data: {
        billtypeCode: values.billtypecode.value,
        transtypeCode: values.transtypecode.value,
        billid: values.busiid.value
      },
      success: data => {
        sscOpenTo(this.props, data.data.system, [
          data.data.url, {
            ...data.data.data,
            scene: "fycx"
          }
        ], this.props.openTo)
      }
    });
  };

   // 处理排序后的模板变化
   handleTempletAfterSort (sortParam,tempId){
    if(sortParam[0].order=='flatscend'){
        this.queryKey.orderByInfo = [];
    }else {
        this.queryKey.orderByInfo = sortParam;
    }
    let sortObj = {};
    sortParam.forEach(item => {
         sortObj[item.field] = item;
    });
    let meta = this.props.meta.getMeta()
    meta[window.presetVar[tempId]].items.forEach(item => {
        //保存返回的column状态，没有则终止order状态
        if(sortObj[item.attrcode]){
            item.order = sortObj[item.attrcode].order;
            item.orderNum = sortObj[item.attrcode].orderNum;
        }else {
            item.order = "flatscend";
            item.orderNum = "";
        }
    })
    this.props.meta.setMeta(meta);
}

  render() {
    const { onRowDoubleClick } = this;
    const { table, search } = this.props;
    const { createSimpleTable } = table;
    let { NCCreateSearch } = search;
    let multiLang = this.props.MutiInit.getIntl(2011);
    let isShow = type => {
      if (this.state.showType == "list" && type == "list") {
        return "show";
      } else if (this.state.showType == "card" && type == "card") {
        return "show";
      } else {
        return "hide";
      }
    };
    let addMoreOnOff = this.data.listRows.length > 0 && Number(this.queryKey.pageinfo.totalPages) > Number(this.queryKey.pageinfo.number)
    return (

        <ProfileStyle
            layout="singleTable"
            {...this.props}
            id="rpBillList"
        >
            <ProfileHead
                title={multiLang && multiLang.get("201103DJCX-0006")}
            >
                <HeadCenterCustom>
                    <NCSelect
                        fieldid="fuzzy-query"
                        className="fuzzyquery"
                        tags
                        supportSearch={true}
                        searchPlaceholder={
                            multiLang && multiLang.get("201103DJCX-0003")
                        }
                        placeholder={multiLang && multiLang.get("201103DJCX-0004")}
                        data={this.state.fuzzyquerychild}
                        onSearch={this.onFuzzyChange.bind(this)}
                        onChange={this.onFuzzySelected.bind(this)}
                    />
                    <i
                        className={`menu-type-icon iconfont ${
                            this.state.menuShowType.type
                            }`}
                        title={this.state.menuShowType.title}
                        onClick={this.menuClick}
                    />
                </HeadCenterCustom>
            </ProfileHead>
            <ProfileSearch>
                {NCCreateSearch(
                  presetVar.searchArea, //模块id
                  {
                    clickSearchBtn: this.searchClick.bind(this), //   点击按钮事件
                    defaultConditionsNum: 1, //默认显示几个查询条件
                    showAdvBtn: false
                  }
                )}
            </ProfileSearch>
            <ProfileBody>
                <div className={`${isShow("list")}`}>
                  <div className="nc-single-table">
                    {createSimpleTable(presetVar.list, {
                        showIndex: true,
                        lazyload: true,
                        onRowDoubleClick,
                        sort: {
                            mode: 'single',
                            backSource: true,
                            sortFun: (sortParam) => {
                                this.handleTempletAfterSort(sortParam, "list")
                                this.orderByClick();
                            }
                        }
                    })} 
                    {/* "201103DJCX-0008":"滑动加载更多" */}
                    <div
                        className='scroll-add-more'
                        style={{ display: addMoreOnOff ? 'block' : 'none' }}
                    >{multiLang && multiLang.get('201103DJCX-0008')}</div>
                  </div>
                </div>
                <div className={isShow("card")}>
                    <WorkbenchDetail
                        ref="detail"
                        btns={this.state.btns}
                        props={this.props}
                        doAction={listButtonClick.bind(this)}
                        getBtns={() => {
                            if (this.queryKey.isComplate == "true") {
                                return ["Print", "Copy"];
                            } else {
                                return ["Print", "Copy", "RemindingApproval"];
                            }
                        }}
                    />
                    <div
                        className='scroll-add-more'
                        style={{ display: addMoreOnOff ? 'block' : 'none' }}
                    >{multiLang && multiLang.get('201103DJCX-0008')}</div>
                </div>
            </ProfileBody>
        </ProfileStyle>
    );
  }
}
RpBillSearch = createPage({
  mutiLangCode: "2011"
})(RpBillSearch);
export default RpBillSearch;
